﻿using Bird.Core;
using Bird.Core.Data;
using Bird.Core.Domain.Projects;
using Bird.Services.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bird.Services.Projects
{
    public partial class ProjectService : IProjectService
    {
        IEventPublisher _eventPublisher;
        IRepository<Project> _repository;

        public ProjectService(IRepository<Project> repository, IEventPublisher eventPublisher)
        {
            _eventPublisher = eventPublisher;
            _repository = repository;
        }

        public Project GetProjectById(int id)
        {
            return _repository.GetById(id);
        }
        public Project[] GetProjectsByCreatorId(int creatorId)
        {
            return _repository.Table.Where(x => x.CreatorUserId == creatorId).ToArray();
        }
        public void DeleteProject(Project project)
        {
            _repository.Delete(project);
            _eventPublisher.EntityDeleted(project);
        }
        public void UpdateProject(Project project)
        {
            _repository.Update(project);
            _eventPublisher.EntityUpdated(project);
        }
        public void InsertProject(Project project)
        {
            _repository.Insert(project);
            _eventPublisher.EntityInserted(project);
        }


        public Core.IPagedList<Project> GetAllProjects(int pageSize, int pageIndex, DateTime? startTime, DateTime? endTime, int? creatorId)
        {
            var query = _repository.Table;
            if (creatorId.HasValue)
                query = query.Where(x => x.CreatorUserId == creatorId);
            if (startTime.HasValue)
                query = query.Where(x => x.CreateTime >= startTime);
            if (endTime.HasValue)
                query = query.Where(x => x.CreateTime <= endTime);
            return new PagedList<Project>(query.OrderBy(p => p.CreateTime), pageSize, pageIndex);
        }
    }
}
